package com.hbnu.Util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtils {
    public static void addCookie(
            String CookieName,
            int time,
            HttpServletRequest request,
            HttpServletResponse response,
            String stuCode,
            String password
    ) {
        Cookie cookie = getCookieByCookieName(CookieName, request);
        if (cookie != null) {
            cookie.setValue(stuCode + "#" + password);
        }
        else {
            cookie = new Cookie(CookieName, stuCode + "#" + password);
        }
        cookie.setMaxAge(time);
        cookie.setPath(request.getContextPath());

        response.addCookie(cookie);
    }

    public static Cookie getCookieByCookieName(
            String CookieName,
            HttpServletRequest request
    ) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(CookieName)) {
                    return cookie;
                }
            }
        }
        return null;
    }
}
